<template>
  <div class="workorder-add">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>新增生产工单</h2>
      <p>创建新的生产工单，系统将自动生成工单编号</p>
    </div>

    <!-- 表单区域 -->
    <el-card class="form-card" shadow="never">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        class="workorder-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工单编号" prop="workorderCode">
              <el-input 
                v-model="formData.workorderCode" 
                placeholder="系统自动生成"
                readonly
                disabled
              >
                <template #suffix>
                  <el-icon><Refresh /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工单名称" prop="workorderName">
              <el-input 
                v-model="formData.workorderName" 
                placeholder="请输入工单名称"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="生产对象" prop="object">
              <el-input 
                v-model="formData.object" 
                placeholder="请输入生产对象"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工单状态" prop="workorderState">
              <el-select 
                v-model="formData.workorderState" 
                placeholder="请选择工单状态"
                style="width: 100%"
              >
                <el-option label="待开始" :value="0" />
                <el-option label="进行中" :value="1" />
                <el-option label="已完成" :value="2" />
                <el-option label="已暂停" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="进度" prop="progress">
              <el-input-number
                v-model="formData.progress"
                :min="0"
                :max="100"
                placeholder="请输入进度百分比"
                style="width: 100%"
              />
              <span class="progress-suffix">%</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工艺流程" prop="processflowId">
              <div class="processflow-select-container">
                <el-select 
                  v-model="formData.processflowId" 
                  placeholder="请选择工艺流程"
                  style="width: calc(100% - 40px)"
                  :loading="processflowLoading"
                  filterable
                  clearable
                  @focus="handleProcessflowFocus"
                >
                  <el-option
                    v-for="flow in processflowList"
                    :key="flow.id"
                    :label="flow.name"
                    :value="flow.id"
                  />
                  <template #empty>
                    <div class="empty-option">
                      <el-icon><Loading /></el-icon>
                      <span>正在加载工艺流程...</span>
                    </div>
                  </template>
                </el-select>
                <el-button 
                  type="primary" 
                  size="small" 
                  :icon="Refresh" 
                  @click="handleRefreshProcessflow"
                  :loading="processflowLoading"
                  style="margin-left: 8px; width: 32px; height: 32px;"
                  title="刷新工艺流程列表"
                />
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注说明" prop="remark">
              <el-input
                v-model="formData.remark"
                type="textarea"
                :rows="4"
                placeholder="请输入备注说明（可选）"
                maxlength="500"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 操作按钮 -->
      <div class="form-actions">
        <el-button @click="handleReset" :disabled="submitLoading">
          <el-icon><Refresh /></el-icon>
          重置
        </el-button>
        <el-button @click="handleCancel">
          <el-icon><Close /></el-icon>
          取消
        </el-button>
        <el-button 
          type="primary" 
          @click="handleSubmit" 
          :loading="submitLoading"
        >
          <el-icon><Check /></el-icon>
          提交
        </el-button>
      </div>
    </el-card>

    <!-- 预览区域 -->
    <el-card class="preview-card" shadow="never" v-if="showPreview">
      <template #header>
        <div class="card-header">
          <span>工单信息预览</span>
          <el-button type="text" @click="showPreview = false">
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
      </template>
      <div class="preview-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="工单编号">
            {{ formData.workorderCode }}
          </el-descriptions-item>
          <el-descriptions-item label="工单名称">
            {{ formData.workorderName }}
          </el-descriptions-item>
          <el-descriptions-item label="生产对象">
            {{ formData.object }}
          </el-descriptions-item>
          <el-descriptions-item label="工单状态">
            <el-tag :type="getStateTagType(formData.workorderState)">
              {{ getStateText(formData.workorderState) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="进度">
            <el-progress 
              :percentage="formData.progress" 
              :color="getProgressColor(formData.progress)"
            />
          </el-descriptions-item>
          <el-descriptions-item label="工艺流程">
            {{ getProcessflowName(formData.processflowId) }}
          </el-descriptions-item>
          <el-descriptions-item label="备注说明" :span="2">
            {{ formData.remark || '无' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, Close, Check, Loading } from '@element-plus/icons-vue'
import { getWriteClient, getReadClient } from '../Urls/AxiosHelper'
import { useRouter } from 'vue-router'

// 接口类型定义
interface WorkorderFormData {
  workorderCode: string
  workorderName: string
  object: string
  workorderState: number
  progress: number
  processflowId: number
  remark?: string
}

interface Processflow {
  id: number
  name: string
}

// 路由
const router = useRouter()

// 响应式数据
const formRef = ref()
const submitLoading = ref(false)
const processflowLoading = ref(false)
const showPreview = ref(false)
const processflowList = ref<Processflow[]>([])

// 表单数据
const formData = reactive<WorkorderFormData>({
  workorderCode: '',
  workorderName: '',
  object: '',
  workorderState: 0,
  progress: 0,
  processflowId: 0,
  remark: ''
})

// 表单验证规则
const formRules = {
  workorderName: [
    { required: true, message: '请输入工单名称', trigger: 'blur' },
    { min: 2, max: 50, message: '工单名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  object: [
    { required: true, message: '请输入生产对象', trigger: 'blur' },
    { min: 2, max: 30, message: '生产对象长度在 2 到 30 个字符', trigger: 'blur' }
  ],
  workorderState: [
    { required: true, message: '请选择工单状态', trigger: 'change' }
  ],
  progress: [
    { required: true, message: '请输入进度', trigger: 'blur' },
    { type: 'number', min: 0, max: 100, message: '进度必须在 0 到 100 之间', trigger: 'blur' }
  ],
  processflowId: [
    { required: true, message: '请选择工艺流程', trigger: 'change' }
  ]
}

// 计算属性
const isFormValid = computed(() => {
  return formData.workorderName && 
         formData.object && 
         formData.workorderState !== undefined && 
         formData.progress !== undefined && 
         formData.processflowId
})

// 方法
const generateWorkorderCode = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')
  
  // 生成格式：WK-YYYYMMDD-HHMMSS
  return `WK-${year}${month}${day}-${hours}${minutes}${seconds}`
}

const getStateText = (state: number) => {
  const stateMap: { [key: number]: string } = {
    0: '待开始',
    1: '进行中',
    2: '已完成',
    3: '已暂停'
  }
  return stateMap[state] || '未知'
}

const getStateTagType = (state: number) => {
  const typeMap: { [key: number]: string } = {
    0: 'info',
    1: 'warning',
    2: 'success',
    3: 'danger'
  }
  return typeMap[state] || 'info'
}

const getProgressColor = (percentage: number) => {
  if (percentage < 30) return '#f56c6c'
  if (percentage < 70) return '#e6a23c'
  return '#67c23a'
}

const getProcessflowName = (id: number) => {
  const flow = processflowList.value.find(item => item.id === id)
  return flow ? flow.name : '未选择'
}

// 处理工艺流程下拉框焦点事件
const handleProcessflowFocus = () => {
  console.log('🎯 工艺流程下拉框获得焦点')
  if (processflowList.value.length === 0) {
    console.log('📝 工艺流程列表为空，开始加载...')
    fetchProcessflowList()
  } else {
    console.log('✅ 工艺流程列表已有数据，无需重新加载')
  }
}

// 手动刷新工艺流程列表
const handleRefreshProcessflow = () => {
  console.log('🔄 手动刷新工艺流程列表')
  fetchProcessflowList()
}

// 获取工艺流程列表
const fetchProcessflowList = async () => {
  try {
    processflowLoading.value = true
    console.log('🔄 开始获取工艺流程列表...')
    console.log('📊 当前processflowList.value:', processflowList.value)
    
    // 使用与proflowlist.vue相同的API调用逻辑
    const apiClient = getReadClient(0)
    console.log('🌐 API客户端基础URL:', apiClient.defaults.baseURL)
    console.log('🔗 完整请求URL:', `${apiClient.defaults.baseURL}/sellreadapi/api/Processs/Processflowlist`)
    
    const response = await apiClient.get('/sellreadapi/api/Processs/Processflowlist', {
      params: { pageindex: 1, pagesize: 1000 }
    })
    
    console.log('📥 工艺流程API完整响应:', response)
    console.log('📥 响应状态码:', response.status)
    console.log('📥 响应数据:', response.data)
    
    if (response.data && response.data.data && response.data.data.data) {
      console.log('✅ API响应格式正确，开始转换数据...')
      console.log('📋 原始数据:', response.data.data.data)
      
      // 转换数据格式以匹配下拉框需求
      const convertedData = response.data.data.data.map((item: any) => ({
        id: item.id,
        name: item.processflowName
      }))
      
      console.log('🔄 转换后的数据:', convertedData)
      processflowList.value = convertedData
      console.log('✅ 设置后的processflowList.value:', processflowList.value)
      console.log('📊 数据长度:', processflowList.value.length)
    } else {
      console.warn('⚠️ 工艺流程API响应格式异常，使用模拟数据')
      console.log('🔍 响应结构分析:')
      console.log('  - response.data:', !!response.data)
      console.log('  - response.data.data:', !!response.data?.data)
      console.log('  - response.data.data.data:', !!response.data?.data?.data)
      
      // 如果API响应格式异常，使用模拟数据作为备选
      processflowList.value = [
        { id: 1, name: '电动汽车电车组装工艺' },
        { id: 2, name: '笔记本电脑主板质量控制工艺' },
        { id: 3, name: '自动洗衣机生产流程' },
        { id: 4, name: '智能手机组装工艺' }
      ]
      console.log('🔄 使用模拟数据:', processflowList.value)
    }
  } catch (error: any) {
    console.error('❌ 获取工艺流程列表失败:', error)
    console.error('❌ 错误详情:', {
      message: error.message,
      status: error.response?.status,
      data: error.response?.data
    })
    
    ElMessage.warning('获取工艺流程列表失败，使用默认数据')
    
    // 出错时使用模拟数据
    processflowList.value = [
      { id: 1, name: '电动汽车电车组装工艺' },
      { id: 2, name: '笔记本电脑主板质量控制工艺' },
      { id: 3, name: '自动洗衣机生产流程' },
      { id: 4, name: '智能手机组装工艺' }
    ]
    console.log('🔄 错误时使用模拟数据:', processflowList.value)
  } finally {
    processflowLoading.value = false
    console.log('🏁 工艺流程加载完成，最终数据:', processflowList.value)
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    // 表单验证
    await formRef.value.validate()
    
    // 确认提交
    await ElMessageBox.confirm(
      '确定要提交这个工单吗？',
      '确认提交',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    submitLoading.value = true
    
    // 准备提交数据 - 匹配后端期望的格式
    // 后端期望格式: WorkorderCode(字符串), WorkorderName(字符串), Object(字符串), 
    // WorkorderState(数字), progress(字符串), ProcessflowId(数字)
    const submitData = {
      WorkorderCode: formData.workorderCode,
      WorkorderName: formData.workorderName,
      Object: formData.object,
      WorkorderState: Number(formData.workorderState),
      progress: String(formData.progress), // 后端期望字符串格式 "85"
      ProcessflowId: Number(formData.processflowId),
      Remark: formData.remark || ''
    }
    
    // 调试信息
    console.log('准备提交的数据:', submitData)
    console.log('API地址: /sellwriteapi/api/Workorder/WorkorderAdd')
    
    // 调用API - 使用相对路径通过代理
    const apiClient = getWriteClient(0)
    console.log('使用的API客户端:', apiClient.defaults.baseURL)
    console.log('完整请求URL:', `${apiClient.defaults.baseURL}/sellwriteapi/api/Workorder/WorkorderAdd`)
    
    const response = await apiClient.post('/sellwriteapi/api/Workorder/WorkorderAdd', submitData, {
      headers: {
        'Content-Type': 'application/json'
      }
    })
    console.log('API响应:', response.data)
    
    if (response.data && response.data.Code === 200) {
      ElMessage.success('生产工单添加成功！')
      
      // 询问是否继续添加
      const continueAdd = await ElMessageBox.confirm(
        '工单添加成功！是否继续添加新的工单？',
        '继续添加',
        {
          confirmButtonText: '继续添加',
          cancelButtonText: '返回列表',
          type: 'success'
        }
      ).catch(() => false)
      
      if (continueAdd) {
        handleReset()
      } else {
        router.push('/orderslist')
      }
    } else {
      ElMessage.error(response.data?.Message || '添加失败')
    }
  } catch (error: any) {
    console.error('提交工单失败:', error)
    
    // 详细的错误信息
    let errorMessage = '提交工单失败，请重试'
    
    if (error.response) {
      // 服务器响应了错误状态码
      console.error('响应错误:', error.response.status, error.response.data)
      
      if (error.response.status === 400) {
        // 400错误通常是验证错误，显示详细错误信息
        const errorData = error.response.data
        if (errorData?.errors) {
          // 显示具体的验证错误
          const validationErrors = Object.values(errorData.errors).flat()
          errorMessage = `数据验证失败: ${validationErrors.join(', ')}`
        } else if (errorData?.title) {
          errorMessage = `验证错误: ${errorData.title}`
        } else {
          errorMessage = `请求数据格式错误 (400): ${errorData?.message || '请检查提交的数据格式'}`
        }
      } else {
        errorMessage = `服务器错误 (${error.response.status}): ${error.response.data?.message || '未知错误'}`
      }
    } else if (error.request) {
      // 请求已发出但没有收到响应
      console.error('网络错误:', error.request)
      errorMessage = '网络连接失败，请检查网络连接或后端服务是否启动'
    } else {
      // 其他错误
      console.error('请求配置错误:', error.message)
      errorMessage = `请求配置错误: ${error.message}`
    }
    
    ElMessage.error(errorMessage)
  } finally {
    submitLoading.value = false
  }
}

// 重置表单
const handleReset = () => {
  formRef.value?.resetFields()
  formData.workorderCode = generateWorkorderCode()
  formData.workorderState = 0
  formData.progress = 0
  formData.processflowId = 0
  formData.remark = ''
  showPreview.value = false
}

// 取消操作
const handleCancel = async () => {
  if (isFormValid.value) {
    try {
      await ElMessageBox.confirm(
        '表单中还有内容，确定要离开吗？',
        '确认离开',
        {
          confirmButtonText: '确定离开',
          cancelButtonText: '继续编辑',
          type: 'warning'
        }
      )
      router.push('/orderslist')
    } catch {
      // 用户取消离开
    }
  } else {
    router.push('/orderslist')
  }
}

// API测试代码已删除

// 生命周期
onMounted(() => {
  // 生成工单编号
  formData.workorderCode = generateWorkorderCode()
  // 获取工艺流程列表
  fetchProcessflowList()
})
</script>

<style scoped>
.workorder-add {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.form-card {
  margin-bottom: 20px;
}

.workorder-form {
  max-width: 800px;
}

.progress-suffix {
  margin-left: 8px;
  color: #909399;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 12px;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.preview-card {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.preview-content {
  margin-top: 16px;
}

/* 工艺流程下拉框样式 */
.processflow-select-container {
  display: flex;
  align-items: center;
  width: 100%;
}

.empty-option {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 12px;
  color: #909399;
  font-size: 14px;
}

.empty-option .el-icon {
  animation: rotate 2s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .workorder-add {
    padding: 10px;
  }
  
  .workorder-form {
    max-width: 100%;
  }
  
  .form-actions {
    flex-direction: column;
  }
  
  .form-actions .el-button {
    width: 100%;
  }
}
</style>
